import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css' // css初始化
import { getToken, setToken, getUrl, setUrl, setUser, setRole } from '@/utils/auth' // 从cookie得到token
import getPageTitle from '@/utils/get-page-title' // 每页标题头
NProgress.configure({ showSpinner: false }) // 进度条

// const whiteList = ['/login'] // 白名单重置列表

router.beforeEach(async(to, from, next) => {
  // 进度条开始
  NProgress.start()

  // 建立标题头
  document.title = getPageTitle(to.meta.title)
  // cookie没有token
  const token = to.query.token
  const url = to.query.url
  const name = to.query.userName
  const userRole = to.query.userRole
  // || getToken()!== token
  console.log(getToken())
  if (!getToken()) {
    if (token) { // cookie没有缓存 && 当前路由为默认路由(路由级判断) '/'
      setToken(token)
      setUrl(url)
      setRole(userRole)
      setUser(name)
      const { roles } = await store.dispatch('user/getInfo', url)
      if (Array.isArray(roles) && roles.length > 0) {
        // 调取路由表进行筛查
        const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
        // 动态加载路由开始
        router.addRoutes(accessRoutes)
        next({ ...to, replace: true })
      } else {
        // 没啥权限，滚!
        NProgress.done()
        console.log(1)
        window.location.replace('http://10.10.8.14:9520/#/')
      }
    } else { // cookie没有token && 当前路由不是默认
      // 没啥权限，滚!
      NProgress.done()
      console.log(2)
      window.location.replace('http://10.10.8.14:9520/#/')
    }
  } else { // cookie有缓存(应该不用判断是不是默认页,直接判断store.getter.roles)
    if (store.getters.roles && store.getters.roles.length > 0) {
      next()
    } else {
      const name = to.query.userName
      const token = to.query.token
      const userRole = to.query.userRole
      if (token) {
        setToken(token)
        setUser(name)
        setRole(userRole)
      }
      const { roles } = await store.dispatch('user/getInfo', getUrl())
      if (Array.isArray(roles) && roles.length > 0) {
        const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
        // 动态加载路由开始
        router.addRoutes(accessRoutes)
        next({ ...to, replace: true })
      } else {
        // 没啥权限，滚!
        NProgress.done()
        console.log(3)
        window.location.replace('http://10.10.8.14:9520/#/')
      }
    }
  }
})

router.afterEach(() => {
  // 结束进度条展示
  NProgress.done()
})
